package ua.ad.feedsreader.actions;


import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.apache.struts2.interceptor.SessionAware;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import com.opensymphony.xwork2.ActionSupport;
import com.sun.org.apache.xml.internal.dtm.ref.DTMNodeList;


public class MostrarSapoGames extends ActionSupport implements SessionAware {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -2647067394523485454L;
	private Map<String, Object> session;
	private Map<String, String> feeds;
	
	@Override
	public String execute() throws Exception {
		//Cria um objeto URL com o endereço do feed de artigos de jogos
		URL url = new URL("http://services.sapo.pt/Games/RSS/GetAllArticles");
		//Cria um DocumentBuilder
		DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		//Gera o documento a partir do stream do objeto URL
		Document xml = db.parse(url.openStream());
		/**
		 * Cria um objeto para suporte XPath no DOM
		 */
		XPath xpath = XPathFactory.newInstance().newXPath();
		//Obtém todos os elementos <item> do RSS
		DTMNodeList items = (DTMNodeList) xpath.evaluate("//channel/item", xml, XPathConstants.NODESET);
		
		feeds = new HashMap<String, String>();
		for (int i = 0; i < items.getLength(); i++) {
		    Node item = items.item(i);
		    String titulo = (String) xpath.evaluate("title/text()", item, XPathConstants.STRING);
		    String link = (String) xpath.evaluate("link/text()", item, XPathConstants.STRING);
		    feeds.put( titulo, link );
		}

		return SUCCESS;
	}
	
	public Map<String, Object> getSession() {
        return session;
    }

	@Override
    public void setSession(Map<String, Object> session) {
        this.session = session;
    }

	/**
	 * @return the feeds
	 */
	public Map<String, String> getFeeds() {
		return feeds;
	}

	/**
	 * @param feeds the feeds to set
	 */
	public void setFeeds(Map<String, String> feeds) {
		this.feeds = feeds;
	}

}
